import re
import time

import pandas as pd
import requests
from rdkit import Chem

pd.options.mode.chained_assignment = None  # default='warn'


# api_url = "http://biotransformer.ca/queries.json"
# todo_d = {"biotransformer_option":"ALLHUMAN", "number_of_steps":1,
# "query_input":"O=C(O)c1ccccc1", "task_type":"PREDICTION" }
# response = requests.post(api_url, json=todo_d)
# id =("").join(re.findall(r"\d+",response.url))
# api_url2 = f"http://biotransformer.ca/queries/{id}.json"
# response2 = requests.get(api_url2)
# result_dict = response2.json()
# print(result_dict["predictions"][0]["biotransformations"][0]["products"][0]["smiles"])

def canonicalize_smiles(smiles):
    mol = Chem.MolFromSmiles(Chem.CanonSmiles(smiles))
    if mol is not None:
        return Chem.MolToSmiles(mol, isomericSmiles=False)
    else:
        return ''


data = pd.read_excel("test_compound_2652.xlsx")
data["biotransformer3.0_product"] = None
print(data.head(1))

for i in range(len(data)):
    try:
        smi = canonicalize_smiles(data["substrate_smiles_canonical"][i])
        todo = {"biotransformer_option": "ALLHUMAN", "number_of_steps": 1, "query_input": smi,
                "task_type": "PREDICTION"}
        api_url = "http://biotransformer.ca/queries.json"
        response = requests.post(api_url, json=todo)
        id = "".join(re.findall(r"\d+", response.url))
        time.sleep(30)
        api_url2 = f"http://biotransformer.ca/queries/{id}.json"
        response2 = requests.get(api_url2)
        result_dict = response2.json()
        try:
            ran = result_dict["predictions"][0]["nr_of_biotransformations"]
            results = []
            for _ in range(ran):
                results.append(result_dict["predictions"][0]["biotransformations"][_]["products"][0]["smiles"])
            data["biotransformer3.0_product"][i] = ",".join(results)
            print(i, "completed", data["biotransformer3.0_product"][i])
        except (Exception,):
            print(i, "error 2")
            try:
                print(i, "status", response2.status_code)
            except (Exception,):
                pass

    except (Exception,):
        print(i, "error 1")

data.to_excel("biotransformer3.xlsx")
